import { history } from 'umi';
import React, { useState, useRef, useEffect, forwardRef, useImperativeHandle } from 'react';
import { PageContainer, FooterToolbar, PageHeader } from '@ant-design/pro-layout';
import SyntaxHighlighter from 'react-syntax-highlighter';
import { dark } from 'react-syntax-highlighter/dist/esm/styles/hljs';
import { CopyOutlined } from '@ant-design/icons';
import CopyToClipboard from 'react-copy-to-clipboard';
import {
  Button,
  Divider,
  message,
  Input,
  Drawer,
  Table,
  Tabs,
  Card,
  Modal,
  Tag,
  Select,
  Descriptions,
  Form,
} from 'antd';
import ProTable from '@ant-design/pro-table';

import { getGroupList } from '../../NameSpace/service';
import { getPassword, getHarborAddress, getUserHarborAccess } from '@/pages/PublicHarbor/service';
import format from '@/utils/format';
import { pullImage } from '../service.js';

const Server = (props, ref) => {

  const [showLogin, setShowLogin] = useState(false);
  const [ShowUpload, setShowUpload] = useState(false);
  // const [baseLine, setBaseLine] = useState('');
  const [loginCmd, setLoginCmd] = useState('');
  const [expires_at, setExpires] = useState(0);
  const [code, setCode] = useState('');
  // const [address, setAddress] = useState('');
  let titleStyle = {
    fontWeight: 'bold',
    marginBottom: '10px',
  };
  let contentStyle = {
    marginBottom: '10px',
    marginLeft: '20px',
  };
  function getLoginPass() {
    // getPassword(props.type).then((res) => {
    getUserHarborAccess(props.type).then((res) => {
      setLoginCmd(res.data.logincmd);
      setExpires(res.data.expires_at);
      setShowLogin(true);
    });
  }

  useImperativeHandle(ref, () => ({
    open: (info={}) => {
      setShowUpload(true);
    },
    close: () => {
      setShow(false);
      setImageId(0);
      setNameSpaceList([]);
      setLoading(false);
      setPullState('waiting')
      form.resetFields()
    },
  }));
  function onFinish(e) {
    setLoading(true);
    setPullState('pending');
    let data_ = { command: e.command };
    if (imageId) {
      data_.imageId = parseInt(imageId);
    }
    pullImage(data_)
      .then(function (res) {
        console.log(res,res.code==0)
        if (res.code == 0) {
          setPullState('success');
          props.success();
        } else {
          setPullState('error');
        }
        setLoading(false);
      })
      .catch(() => {
        setLoading(false);
        setPullState('error');
      });
  }
  useEffect(() => {
    getHarborAddress(props.type).then(res => {
      if (res && res.code === 0) {
        const address = res.data.harborAddress;
        const code = `$ sudo docker tag {镜像名称}:{版本名称} ${address}/{镜像名称}:{版本名称}\n$ sudo docker push ${address}/{镜像名称}:{版本名称}`;
        setCode(code);
      } else {
        message.error('获取harborAddress失败');
      }
    })
  }, [])

  return (
    <div>
      <Modal
        title="客户端上传"
        width="800px"
        visible={ShowUpload}
        footer={null}
        onCancel={() => {
          setShowUpload(false);
        }}
        maskClosable={false}
      >
        <div className="title" style={titleStyle}>
          前提条件：
        </div>
        <div className="content" style={contentStyle}>
          准备一台计算机，要求计算机与当前集群harbor在同一网段内，且安装的容器引擎版本必须为1.11.2及以上
        </div>
        <div className="title" style={titleStyle}>
          操作步骤：
        </div>
        <div className="content" style={contentStyle}>
          Step 1. 以root用户登录容器引擎所在的虚拟机，在/etc/hosts文件配置harbor域名解析
        </div>
        <div className="content" style={contentStyle}>
          Step 2. 获取登录访问指令，并复制到节点上执行{' '}
          <span
            style={{ color: '#1A90FF', cursor: 'pointer' }}
            onClick={() => {
              getLoginPass();
            }}
          >
            生成临时登录指令
          </span>
        </div>
        <div className="content" style={contentStyle}>
          Step 3. 上传镜像
        </div>
        <div style={{margin: '0 40px'}}>
          <SyntaxHighlighter language="bash" style={dark}>
            {code}
          </SyntaxHighlighter>
        </div>

      </Modal>
      <Modal
        title="登录指令"
        width="800px"
        visible={showLogin}
        footer={null}
        onCancel={() => {
          setShowLogin(false);
        }}
        maskClosable={false}
      >
        <div style={{ width: '750px', marginBottom: '10px' }} className="pre-block">
          <div>
            {' '}
            {loginCmd}{' '}
            <CopyToClipboard
              text={loginCmd}
              onCopy={() => {
                message.info('复制成功');
              }}
            >
              <CopyOutlined style={{ cursor: 'pointer' }} />
            </CopyToClipboard>
          </div>
        </div>

        <p>过期时间:{format(expires_at * 1000)}</p>
      </Modal>
    </div>
  );
};
const FServer = React.forwardRef(Server);
export default FServer;
